<?php 

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\Loader;
use app\admin\controller\Admin;

class Technique extends Admin
{
    /**
     * 主页列表展示
     * @return [type] [description]
     */
    public function index()
    {
        
        $post = input('post.');
        // var_dump($post); 
        if (!empty($post['search'])) {
             $result = db('construction_organization_design as cod, dj_project_application as pa')->field('cod.id, pa.project_name, cod.design_name, cod.organization_user, cod.status')->where('cod.paid = pa.id')->where(array('pa.project_name'=>array('like', '%'.$post['search'].'%')))->paginate(6);
        } else {
            $result = db('construction_organization_design as cod, dj_project_application as pa')->field('cod.id, pa.project_name, cod.design_name, cod.organization_user, cod.status')->where('cod.paid = pa.id')->paginate(6);
        }
        return view('admin@technique/index', [
            'list' => $result
        ]);
    }


    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        if (!Request::instance()->isAjax()) 
        {
                $this->error('你是不是迷路了?', '/');
        }

        // 查询指定用户信息 显示查询
        $row = db('construction_organization_design')->find($id);
        if ($row === null) {
            $info['status'] = false;
            $info['title'] = '查无数据';
            $info['datas'] = '查无数据,请您重试!';
        } else {
            $info['status'] = true;
            $info['title'] = $row['project_name'];
            $info['data'] = $row;
        }
        return json($info);
    }




    /**
     * 渲染增加页面
     */
    public function create()
    {
        $result = db('project_application')->field(['id', 'project_name'])->select();
        // var_dump($result); die;
        return view('admin@technique/add', [
            'list' => $result
        ]);
    }

    /**
     * 执行添加
     */
    public function save(Request $request)
    {
        $data = $request->post();
        $data['design_name'] = htmlentities($data['design_name']);
        $data['organization_user'] = htmlentities($data['organization_user']);
        $file = request()->file('organization_design');
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads\2018');
            if($info){
                $filearr = ['doc', 'txt'];
                $data['organization_design'] = '/uploads/'.$info->getSaveName();
                if(!in_array(pathinfo($data['organization_design'], PATHINFO_EXTENSION),$filearr)){
                     return $this->error('文件格式不正确,请上传doc,txt文件');
                  // echo "文件格式不正确,请上传doc,txt文件";
                  // die;
                }
                $res =explode('\\', $data['organization_design']);
                $filesa=implode('/',$res);
                $data['organization_design'] = $filesa;
            } else {
                echo $file->getError();
            }
        } else {
            $data['organization_design'] = '';
            return $this->error('请上传您的文件');
        }
        $id = db('project_application')->field('id')->where(['project_name'=>$data['project_name']])->find();
        $data = [
            'paid' => $id['id'],
            'project_name' => $data['project_name'],
            'design_name' => $data['design_name'],
            'organization_user' => $data['organization_user'],
            'organization_design' => $data['organization_design']
        ];

        $result = db('construction_organization_design')->insert($data);
        if ($result > 0) {
            return $this->success('添加成功!', url('admin/technique/index'));
        } else {
            return $this->error('添加失败!');
        }

    }

    /**
     * 渲染编辑页面
     */
    public function edit($id)
    {
        $list = db('construction_organization_design')->find($id);
        // var_dump($list); exit;
        return view('admin@technique/edit', [
            'list' => $list
        ]);
    }

    /**
     * 更新项目
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function update(Request $request, $id)
    {
        $info = $request->put();
        // var_dump($info);
        $id = $info['id'];
        $data = [
            'organization_user'          => htmlentities($info['organization_user'])
        ];
        $result = db('construction_organization_design')->where('id', $id)->update($data);
        // var_dump($result); die;
        if ($result > 0) {
            return $this->success('更新成功!', url('admin/technique/index'));
        } else {
            return $this->error('您未做任何修改!');
        }
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $result = db('construction_organization_design')->delete($id);
        if ($result > 0) {
            $info['status'] = true;
            $info['id'] = $id;
            $info['info'] = 'ID为'.$id.'的项目删除成功!';
        }else{
            $info['status'] = false;
            $info['id'] = $id;
            $info['info'] = '删除失败';
        }


        // echo json_encode($result);
        return json($info);
    }


    // 导出
    public function export()
    {
         //利用筛选条件查询
         $list = db('construction_organization_design')->select();
         // var_dump($list);
         $indexKey = array('id', 'paid', 'project_name', 'design_name', 'organization_design', 'organization_user', 'status');
         //excel表头内容
         $header = array('id'=>'编号','paid'=>'项目编号','project_name'=>'项目名称','design_name'=>'施组设计书','organization_design'=>'文件路径','organization_user'=>'编制人','status'=>'状态');
         array_unshift($list,$header);//将查询到的订单数据和表头内容合并,构造成数组list
         echo '<pre>';print_r($list);

         $this->toExcel($list,'1',$indexKey,1,true);
         // var_dump($list);
    }




    /** 
     * 创建(导出)Excel数据表格 
     * @param  array   $list        要导出的数组格式的数据 
     * @param  string  $filename    导出的Excel表格数据表的文件名 
     * @param  array   $indexKey    $list数组中与Excel表格表头$header中每个项目对应的字段的名字(key值) 
     * @param  array   $startRow    第一条数据在Excel表格中起始行 
     * @param  [bool]  $excel2007   是否生成Excel2007(.xlsx)以上兼容的数据表 
     * 比如: $indexKey与$list数组对应关系如下: 
     *     $indexKey = array('id','username','sex','age'); 
     *     $list = array(array('id'=>1,'username'=>'YQJ','sex'=>'男','age'=>24)); 
     */  

    function toExcel($list,$filename,$indexKey,$startRow=1,$excel2007=false){  
        //文件引入 
        // echo $pe['host_root'].'include/class/PHPExcel.php';die; 
        // include($pe['host_root'].'include/vendor/PHPExcel.php');  
        // include($pe['host_root'].'include/class/PHPExcel/Writer/Excel2007.php');
        // 
        include '../vendor/PHPExcel/PHPExcel.php';
        include '../vendor/PHPExcel/PHPExcel/IOFactory.php';
        include '../vendor/PHPExcel/PHPExcel/Writer/Excel2007.php';
        // 
        Loader::import('PHPExcel.PHPExcel');
        Loader::import('PHPExcel.PHPExcel.IOFactory');
        // Loader::import('PHPExcel.PHPExcel.Writer.Excel2007');
        $objPHPExcel = new \PHPExcel();  

        var_dump($objPHPExcel);
        
        ob_end_clean();
        if(empty($filename)) $filename = time();  
        if( !is_array($indexKey)) return false;  

        $header_arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');  
        //初始化PHPExcel()  

        //设置保存版本格式  
        if($excel2007){  
            $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);  
            $filename = $filename.'.xlsx';  
        }else{  
            $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);  
            $filename = $filename.'.xls';  
        }  

        //接下来就是写数据到表格里面去  
        $objActSheet = $objPHPExcel->getActiveSheet();  
        //$startRow = 1;  
        // var_dump($list);die;
        foreach ($list as $row) {  
            foreach ($indexKey as $key => $value){  
                //这里是设置单元格的内容  
                $objActSheet->setCellValue($header_arr[$key].$startRow,$row[$value]);  
            }  
            $startRow++;  
        }  

        // 下载这个表格，在浏览器输出  
        header("Pragma: public");  
        header("Expires: 0");  
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
        header("Content-Type:application/force-download");  
        header("Content-Type:application/vnd.ms-execl");  
        header("Content-Type:application/octet-stream");  
        header("Content-Type:application/download");;  
        header('Content-Disposition:attachment;filename='.$filename.'');  
        header("Content-Transfer-Encoding:binary");  
        $objWriter->save('php://output');  
    }

    public function _empty(Request $request)
    {
        return view('/error');
    }






}








